package com.hxzy.controller.anonymous.sms;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hxzy.common.constans.RedisConstans;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.resp.R;
import com.hxzy.controller.anonymous.sms.req.PhoneReq;
import com.hxzy.controller.anonymous.sms.req.ValidateSMSReq;
import com.hxzy.entity.Merchandiser;
import com.hxzy.service.MerchandiserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author wy
 * @Description 短信发送
 * @Date 2023/9/6 9:28
 * @Version 1.0
 */
@Api(tags = "公共API-短信验证码")
@RestController
@RequestMapping(value = "/anon/sms")
public class SMSController {

    @Autowired
    private RedisTemplate  redisTemplate;

    /**
     * 商户表
     */
    @Autowired
    private MerchandiserService  merchandiserService;

    @ApiOperation(value = "发送短信验证码")
    @PostMapping(value = "/register")
    public R  registerSms(@RequestBody @Valid PhoneReq req){

       //验证手机号验证码是否还存在（未过期）
       String redisKey= RedisConstans.getRedisKey(RedisConstans.SMS_KEY,req.getPhone());
       Boolean hasKey = this.redisTemplate.hasKey(redisKey);
       if(hasKey){
           return R.build(AckCode.SMS_EXISTS);
       }

       //再判断merchandiser商家表是否已经存在这个手机号
        LambdaQueryWrapper<Merchandiser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchandiser::getLoginName,req.getPhone());
        long count = this.merchandiserService.count(queryWrapper);
        if(count>0){
           return R.build(AckCode.EXISTS_VALUE_PHONE);
        }

        //开始发送
        int num=new Random().nextInt(900000)+100000;
        String code=num+"";

        //一会集成  短信API操作

        //存储到redis中
        this.redisTemplate.opsForValue().set(redisKey,num,RedisConstans.SMS_EXPIRED_MINUTES, TimeUnit.MINUTES);

        //发回数据给前端
        Map<String,Integer>  hashMap=new HashMap();
        hashMap.put("seconds", RedisConstans.SMS_EXPIRED_MINUTES*60);

        return R.okHasData(hashMap);
    }


    /**
     * 这个是给form表自定义验证规则使用的，不能单独调用
     * @param phone
     * @return
     */
    @ApiOperation(value = "验证手机号是否在商户表中存在")
    @GetMapping(value = "/valid/{phone}")
    public R merchandiserExistsPhone(@PathVariable(value = "phone") String phone){
        if(StrUtil.isBlank(phone)){
            return R.okHasData(AckCode.PHONE_NUMBER_NOTNULL.getMsg());
        }
        String reg="0?(13|15|17|18|14|19)[0-9]{9}";
        boolean match = ReUtil.isMatch(reg, phone);
        if(!match){
            return R.okHasData(AckCode.PHONE_NUMBER_ERROR.getMsg());
        }

        //再判断merchandiser商家表是否已经存在这个手机号
        LambdaQueryWrapper<Merchandiser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchandiser::getLoginName,phone);
        long count = this.merchandiserService.count(queryWrapper);
        if(count>0){
            return R.okHasData(AckCode.EXISTS_VALUE_PHONE.getMsg());
        }

        return R.ok();
    }

    @ApiOperation(value = "验证码的有效性")
    @PostMapping(value = "/validate")
    public R checkSmsCode(@RequestBody @Valid ValidateSMSReq req){

        String redisKey= RedisConstans.getRedisKey(RedisConstans.SMS_KEY,req.getPhone());
        Object redisValue = this.redisTemplate.opsForValue().get(redisKey);
        if(Objects.isNull(redisValue)){
            return R.build(AckCode.CODE_NOT_FOUND);
        }

        if(!redisValue.toString().equalsIgnoreCase(req.getCode())){
            return R.build(AckCode.CODE_ERROR);
        }
        //删除
        this.redisTemplate.delete(redisKey);
        return R.ok();
    }


}
